package cn.sn.service.impl;

import cn.sn.constant.JwtClaimsConstant;
import cn.sn.constant.MessageConstant;
import cn.sn.dto.UserLoginDTO;
import cn.sn.entity.User;
import cn.sn.exception.AccountNotFoundException;
import cn.sn.exception.PasswordErrorException;
import cn.sn.mapper.LoginMapper;
import cn.sn.properties.JwtProperties;
import cn.sn.service.IndexService;
import cn.sn.utils.IpUtils;
import cn.sn.utils.JwtUtil;
import cn.sn.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author: SuNing
 * @date: 2023/9/19 20:11
 * @version: 1.0
 */
@Service
@RequiredArgsConstructor
public class IndexServiceImpl implements IndexService {

    private final IpUtils ipUtils;

    private final JwtProperties jwtProperties;

    private final LoginMapper loginMapper;

    /**
     * 登录
     *
     * @param userLoginDTO 用户登录dto
     * @return {@link LoginVO}
     */
    @Override
    public LoginVO login(UserLoginDTO userLoginDTO) {
        // 1.根据用户名查询账好是否存在
        User user = loginMapper.selectUser(userLoginDTO.getLogin_name());

        // 2. 判断各种异常
        if (Objects.isNull(user)) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 加密判断
        String password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        if (!password.equals(user.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        // 更新数据
        user.setLoginIp(ipUtils.getClientIp());
        user.setLoginDate(LocalDateTime.now());
        user.setUpdateDate(LocalDateTime.now());
        loginMapper.updateSysUser(user);

        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                map);

        return LoginVO.builder().token(token).build();
    }
}
